import 'package:flutter/material.dart';

enum TriangleDirection { left, top, right, bottom }

class Triangle extends StatelessWidget {
  final double size;
  final Color color;
  final TriangleDirection direction;

  const Triangle({Key? key, required this.size, required this.color, required this.direction}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      size: direction == TriangleDirection.left || direction == TriangleDirection.right ? Size(size, size * 2) : Size(size * 2, size),
      painter: _Painter(color, direction),
    );
  }
}

class _Painter extends CustomPainter {
  final Color color;
  final TriangleDirection direction;

  _Painter(this.color, this.direction);

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint();
    paint.isAntiAlias = true;
    paint.color = color;
    paint.strokeCap = StrokeCap.round;
    paint.strokeJoin = StrokeJoin.round;
    paint.style = PaintingStyle.fill;
    Path path = Path();
    path.fillType = PathFillType.evenOdd;
    if (direction == TriangleDirection.left) {
      path.addPolygon([Offset(size.width, 0), Offset(size.width, size.height), Offset(0, size.height / 2)], true);
    } else if (direction == TriangleDirection.top) {
      path.addPolygon([Offset(0, size.height), Offset(size.width, size.height), Offset(size.width / 2, 0)], true);
    } else if (direction == TriangleDirection.right) {
      path.addPolygon([const Offset(0, 0), Offset(0, size.height), Offset(size.width, size.height / 2)], true);
    } else if (direction == TriangleDirection.bottom) {
      path.addPolygon([const Offset(0, 0), Offset(size.width, 0), Offset(size.width / 2, size.height)], true);
    }
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant _Painter old) {
    return old.color != color || old.direction != direction;
  }
}
